package net.schastny.shopmanager.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import net.schastny.shopmanager.domain.BaseOrder;
import net.schastny.shopmanager.domain.PreOrder;

@Repository
public class PreOrderDAOImpl implements PreOrderDAO {
	
	/*Аннотация позволяет автоматически установить значение поля SessionFactory.
	 */
	@Autowired
	private SessionFactory sessionFactory;
	
	public void addPreOrder(PreOrder preorder) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().save(preorder);
	}
	
	@SuppressWarnings("unchecked")
	public List<PreOrder> listPreOrder() {
		// TODO Auto-generated method stub
		return sessionFactory.getCurrentSession().createQuery("from PreOrder")
	            .list();
	}

	public void removePreOrder(Integer id) {
		// TODO Auto-generated method stub
		PreOrder preorder = (PreOrder) sessionFactory.getCurrentSession().load(
				PreOrder.class, id);
        if (null != preorder) {
            sessionFactory.getCurrentSession().delete(preorder);
        }
	}

	public PreOrder getPreOrder(Integer id) {
		// TODO Auto-generated method stub
		return 	(PreOrder) sessionFactory.getCurrentSession().createQuery("FROM PreOrder as p WHERE p.id="+id).uniqueResult();
	}

	public void editPreOrder(PreOrder preorder) {
	// TODO Auto-generated method stub
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		System.out.println("----------------- existingBaseOrder = "+preorder.toString());		
		System.out.println("----------------- getPreorderId = "+preorder.getPreorderId());			
		// Retrieve existing person via id
		PreOrder existingPreOrder = (PreOrder) session.get(PreOrder.class, preorder.getPreorderId());
		System.out.println("----------------- existingBaseOrder = "+(existingPreOrder==null));
		// Assign updated values to this person
		existingPreOrder.setPreorderColor(preorder.getPreorderColor());
		existingPreOrder.setPreorderUserId(preorder.getPreorderUserId());
		existingPreOrder.setPreorderCount(preorder.getPreorderCount());
		existingPreOrder.setPreorderCountry(preorder.getPreorderCountry());
		existingPreOrder.setPreorderPrice(preorder.getPreorderPrice());
		existingPreOrder.setPreorderShopId(preorder.getPreorderShopId());
		existingPreOrder.setPreorderSize(preorder.getPreorderSize());		
		existingPreOrder.setPreorderSn(preorder.getPreorderSn());
		existingPreOrder.setPreorderUrl(preorder.getPreorderUrl());

		// Save updates
	session.save(existingPreOrder);
		
		
	}
	
	

}
